package com.cfh.springcloudserver.controller;


import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RemoteAppEventReceiveController implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    @PostMapping("/receive/remote/event")
    public String receive(@RequestBody Map<String, Object> data) {

        String sender = (String) data.get("sender");
        Object value = data.get("value");
        String type = (String) data.get("type");
        publisher.publishEvent(new SenderRemoteAppEvent(value, sender));
        return "received";
    }

    private static class SenderRemoteAppEvent extends ApplicationEvent {
        private String sender;

        public SenderRemoteAppEvent(Object source, String sender) {
            super(source);
            this.sender = sender;
        }
        public String getSender() {
            return sender;
        }
    }

    @EventListener
    @Async
    public void onEvent(SenderRemoteAppEvent event) {
        System.out.printf("事件来自 %s 应用 , 事件源：%s", event.getSender(), event.getSource());
    }
}
